package org.jeecg.modules.withdraw;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.doctor.entity.Doctor;
import org.jeecg.common.modules.doctor.service.IDoctorService;
import org.jeecg.common.modules.doctor.vo.DoctorAccountInfoReqVo;
import org.jeecg.common.modules.withdraw.vo.WithDrawReqVo;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.enums.WithdrawRecordStatusEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.modules.withdraw.entity.WithdrawRecord;
import org.jeecg.common.modules.withdraw.service.IWithdrawRecordService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.vo.ResultVo;
import org.jeecg.modules.withdraw.vo.WithDrawResponseVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: withdraw_record
 * @Author: jeecg-boot
 * @Date:   2020-09-10
 * @Version: V1.0
 */
@Api(tags="withdraw_record")
@RestController
@RequestMapping("/carry/withdrawRecord")
@Slf4j
public class WithdrawRecordController extends JeecgController<WithdrawRecord, IWithdrawRecordService> {
	@Autowired
	private IWithdrawRecordService withdrawRecordService;

	@Resource
	private IDoctorService doctorService;

	
	/**
	 * 分页列表查询
	 *
	 * @param withdrawRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "withdraw_record-分页列表查询")
	@ApiOperation(value="withdraw_record-分页列表查询", notes="withdraw_record-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(WithdrawRecord withdrawRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		//（1）分页数据开始的记录数
		int dataStart = (pageNo - 1) * pageSize;

		//先查询信息
		String doctorName = req.getParameter("doctorName");
		String mobile     = req.getParameter("mobile");

		List<WithDrawReqVo> withDrawReqVos = withdrawRecordService.getWithDrawInfo(doctorName,mobile,dataStart,pageSize);

		List response = new ArrayList();
		for(WithDrawReqVo one:withDrawReqVos){
			WithDrawResponseVo withVo = this.initWithDrawResponseVo(one);
			response.add(withVo);
		}

		//（2）获取总条数
		Integer count = withdrawRecordService.getWithDrawCount(doctorName,mobile);

		//（3）组织分页的返回数据
		ResultVo vo = this.initResultVo(response,count,pageNo,pageSize);
		return Result.ok(vo);
	}

	 /**
	  * 组合返回的信息
	  * @param withDrawReqVos
	  * @param count
	  * @param pageNo
	  * @param pageSize
	  * @return
	  */
	 private ResultVo initResultVo(List withDrawReqVos, Integer count, Integer pageNo, Integer pageSize){
		 ResultVo vo = new ResultVo();
		 double dCount    = Double.valueOf(count);       //查询的数据总条数
		 double dPageSize = Double.valueOf(pageSize);    //每页显示的条数
		 int pages = (int) Math.ceil(dCount / dPageSize);//页码数量

		 vo.setCurrent(pageNo);
		 vo.setOrders(new ArrayList<>());
		 vo.setRecords(withDrawReqVos);
		 vo.setPages(pages);
		 vo.setSize(pageSize);
		 vo.setTotal(count);
		 return vo;
	 }

	 /**
	  * 组合提现的信息
	  * @param withDrawReqVo
	  * @return
	  */
	 private WithDrawResponseVo initWithDrawResponseVo(WithDrawReqVo withDrawReqVo){
		 WithDrawResponseVo vo = new WithDrawResponseVo();
		 vo.setId(withDrawReqVo.getId());
		 vo.setDoctorId(withDrawReqVo.getDoctorId());
		 vo.setDoctorInfo(withDrawReqVo.getDoctorName()+" - "+withDrawReqVo.getMobile());
		 vo.setAmount(withDrawReqVo.getAmount());
		 vo.setAccountInfo(
		 		withDrawReqVo.getBankName()+" - " +
		 		withDrawReqVo.getAccountName()+" - " +
		 		withDrawReqVo.getAccountNo()
		 );
		 vo.setCreateTime(withDrawReqVo.getCreateTime());
		 vo.setCreateBy(withDrawReqVo.getCreateBy());
		 vo.setStatus(withDrawReqVo.getStatus());
		 vo.setReason(withDrawReqVo.getReason());
		 vo.setTaxRatio(withDrawReqVo.getTaxRatio());
		 vo.setTaxFee(withDrawReqVo.getTaxFee());
		 vo.setReceipt(withDrawReqVo.getReceipt());
		 return vo;
	 }

	 /**
	  * 医生全部提现
	  */
	 @AutoLog(value = "withdraw_record-全部提现")
	 @ApiOperation(value="withdraw_record-全部提现", notes="withdraw_record-全部提现")
	 @PostMapping(value = "/withdrawalAll")
//	 public Result<?> withdrawalAll(@RequestParam(name="id",required=true) String id) {
	 public Result<?> withdrawalAll(@RequestBody Doctor doctor) {

		Doctor doctorInfo = doctorService.getById(doctor.getId());
	    if (Objects.isNull(doctorInfo)){
	    	 return Result.error("未获取到医生信息");
	    }
		Result result = withdrawRecordService.withdraw(doctorInfo.getId(),doctorInfo.getName());
		return Result.ok(result);
	 }

	 /**
	  * 财务打款操作
	  */
	 @AutoLog(value = "withdraw_record-财务打款操作")
	 @ApiOperation(value="withdraw_record-全部提现", notes="withdraw_record-全部提现")
	 @PostMapping(value = "/drawalOperate")
	 public Result<?> withdrawalOperate(@RequestBody WithdrawRecord withdrawRecord) {
		 Integer status = withdrawRecord.getStatus();
		 String reason  = withdrawRecord.getReason();
		 String id      = withdrawRecord.getId();

	 	 //处理操作的状态
		 WithdrawRecordStatusEnum statusEnum;
	 	 if(status == 1){
			 statusEnum = WithdrawRecordStatusEnum.AGREE;
		 }else{
			 statusEnum = WithdrawRecordStatusEnum.REFUND;
		 }

	 	 //获取管理员的信息
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Result res = withdrawRecordService.audit(statusEnum,sysUser.getUsername(),reason,id);
		 return Result.ok(res);
	 }

	/**
	 *   添加
	 *
	 * @param withdrawRecord
	 * @return
	 */
	@AutoLog(value = "withdraw_record-添加")
	@ApiOperation(value="withdraw_record-添加", notes="withdraw_record-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WithdrawRecord withdrawRecord) {
		withdrawRecordService.save(withdrawRecord);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param withdrawRecord
	 * @return
	 */
	@AutoLog(value = "withdraw_record-编辑")
	@ApiOperation(value="withdraw_record-编辑", notes="withdraw_record-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WithdrawRecord withdrawRecord) {
		withdrawRecordService.updateById(withdrawRecord);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "withdraw_record-通过id删除")
	@ApiOperation(value="withdraw_record-通过id删除", notes="withdraw_record-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		withdrawRecordService.removeById(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "withdraw_record-批量删除")
	@ApiOperation(value="withdraw_record-批量删除", notes="withdraw_record-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.withdrawRecordService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "withdraw_record-通过id查询")
	@ApiOperation(value="withdraw_record-通过id查询", notes="withdraw_record-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WithdrawRecord withdrawRecord = withdrawRecordService.getById(id);
		if(withdrawRecord==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(withdrawRecord);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param withdrawRecord
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WithdrawRecord withdrawRecord) {
        return super.exportXls(request, withdrawRecord, WithdrawRecord.class, "withdraw_record");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WithdrawRecord.class);
    }

}
